package com.caipin.controller;

import com.caipin.domain.excel.Lecturer;
import com.caipin.domain.table.Teacher;
import com.caipin.domain.table.TeacherWork;
import com.caipin.domain.web.PageBean;
import com.caipin.domain.web.ResultJson;
import com.caipin.service.TeacherManagementService;
import com.caipin.utils.ImportExcel;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: zhunian0322@163.com
 * @DateTime: 2020-08-01 9:10
 * @Description: TODO
 */
@RestController
@RequestMapping({"/teacherManagement"})
public class TeacherManagementController {
    private static final Logger log = LoggerFactory.getLogger(com.caipin.controller.TeacherManagementController.class);

    @Autowired
    private TeacherManagementService teacherManagementService;

    @Value("${faceImage.physicalPath}")
    private String physicalPath;

    @Value("${faceImage.teacherPath}")
    private String teacherImagePath;

    @PostMapping({"/teacherInformationImport"})
    public Object teacherInformationImport(@RequestParam("teacher") MultipartFile file, HttpServletRequest request) throws IOException {
        InputStream inputStream = file.getInputStream();
        List<Teacher> teacherList = ImportExcel.importExcel(inputStream, 1, 0, Teacher.class);
        int count = this.teacherManagementService.importTeacherToMysql(teacherList);
        Map<String, Integer> map = new HashMap<>();
        map.put("count", Integer.valueOf(count));
        return ResultJson.ok(map);
    }

    @GetMapping({"/teacherInformationList"})
    public Object teacherInformationList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize) {
        PageBean<Teacher> pageBean = this.teacherManagementService.findTeacherList(pageNum, pageSize);
        return ResultJson.ok(pageBean);
    }

    @DeleteMapping({"/delTeacherInformation/{teacherId}"})
    public Object delTeacherInformation(@PathVariable("teacherId") String id) {
        this.teacherManagementService.delTeacher(id);
        return ResultJson.ok();
    }

    @GetMapping({"/getTeacherInformation/{teacherId}"})
    public Object getTeacherInformation(@PathVariable("teacherId") String id) {
        Teacher teacher = this.teacherManagementService.findTeacherById(id);
        return ResultJson.ok(teacher);
    }

    @PostMapping({"/addTeacherInformation"})
    public Object addTeacherInformation(@RequestBody Teacher teacher) {
        this.teacherManagementService.addTeacher(teacher);
        return ResultJson.ok();
    }

    @PutMapping({"/modifyTeacherInformation"})
    public Object modifyTeacherInformation(@RequestBody Teacher teacher) {
        this.teacherManagementService.updateTeacher(teacher);
        return ResultJson.ok();
    }

    @PutMapping({"/cleanTeacherWork"})
    public Object cleanTeacherWork() {
        this.teacherManagementService.cleanTeacherWork();
        return ResultJson.ok();
    }

    @PostMapping({"/teacherWorkImport"})
    public Object teacherWorkImport(@RequestParam("teacherWork") MultipartFile file, HttpServletRequest request) throws IOException {
        String filename = file.getOriginalFilename();
        log.info(filename);
        String name = filename.substring(0, filename.lastIndexOf("."));
        String[] strings = name.split("-");
        String building = strings[0];
        String grade = strings[1];
        String classroom = strings[2];
        InputStream inputStream = file.getInputStream();
        List<TeacherWork> teacherWorkList = new ArrayList<>();
        HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
        HSSFSheet teacherSheet = workbook.getSheet(");
                HSSFSheet courseSheet = workbook.getSheet(");
                        Map<String, Lecturer> map = new HashMap<>();
        int i;
        for (i = 1; i <= teacherSheet.getLastRowNum(); i++) {
            HSSFRow row = teacherSheet.getRow(i);
            if (row != null && row
                    .getCell(0) != null && row
                    .getCell(1) != null && row
                    .getCell(2) != null && row
                    .getCell(0).getCellType() != CellType.BLANK && row
                    .getCell(1).getCellType() != CellType.BLANK && row
                    .getCell(2).getCellType() != CellType.BLANK) {
                String courseName = row.getCell(0).getStringCellValue();
                String teacherName = row.getCell(1).getStringCellValue();
                String teacherId = row.getCell(2).getStringCellValue();
                Lecturer lecturer = new Lecturer(courseName, teacherName, teacherId);
                map.put(courseName, lecturer);
            }
        }
        for (i = 1; i < courseSheet.getLastRowNum(); i++) {
            HSSFRow row = courseSheet.getRow(i);
            for (int j = 1; j < row.getLastCellNum(); j++) {
                HSSFCell cell = row.getCell(j);
                if (cell != null && cell.getCellType() != CellType.BLANK) {
                    String courseName = cell.getStringCellValue();
                    int sections = i;
                    int week = j;
                    TeacherWork teacherWork = (new TeacherWork()).setTeacherName(((Lecturer)map.get(courseName)).getTeacherName()).setTeacherId(((Lecturer)map.get(courseName)).getTeacherId()).setCourseName(courseName).setGrade(grade).setWeek(Integer.valueOf(week)).setSections(Integer.valueOf(sections)).setBuilding(building).setClassroom(classroom);
                    teacherWorkList.add(teacherWork);
                }
            }
        }
        int count = this.teacherManagementService.importTeacherWorkToMysql(teacherWorkList);
        Map<String, Integer> mapResult = new HashMap<>();
        mapResult.put("count", Integer.valueOf(count));
        return ResultJson.ok(mapResult);
    }

    @GetMapping({"/teacherWorkList"})
    public Object teacherWorkList(@RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum, @RequestParam(value = "pageSize", required = false, defaultValue = "5") Integer pageSize, @RequestParam(value = "teacherId", required = false) String teacherId, @RequestParam(value = "teacherName", required = false) String teacherName, @RequestParam(value = "course", required = false) String courseName, @RequestParam(value = "grade", required = false) String grade, @RequestParam(value = "clbum", required = false) String clbum, @RequestParam(value = "week", required = false) Integer week, @RequestParam(value = "sections", required = false) Integer sections, @RequestParam(value = "location", required = false) String classroom) {
        PageBean<TeacherWork> pageBean = null;
        if (teacherId != null) {
            pageBean = this.teacherManagementService.findTeacherWorkList(pageNum, pageSize, teacherId);
        } else if (teacherName == null && courseName == null && grade == null && clbum == null && week == null && sections == null && classroom == null) {
            pageBean = this.teacherManagementService.findTeacherWorkList(pageNum, pageSize);
        } else {
            pageBean = this.teacherManagementService.findTeacherWorkList(pageNum, pageSize, teacherName, courseName, grade, clbum, week, sections, classroom);
        }
        return ResultJson.ok(pageBean);
    }

    @DeleteMapping({"/delTeacherWork/{teacherWorkId}"})
    public Object delTeacherWork(@PathVariable("teacherWorkId") Long id) {
        this.teacherManagementService.delTeacherWorkById(id);
        return ResultJson.ok();
    }

    @DeleteMapping({"/delTeacherWorkList"})
    public Object delTeacherWorkList(@RequestBody List<Long> ids) {
        int count = this.teacherManagementService.delTeacherWorkListByIds(ids);
        Map<String, Integer> map = new HashMap<>();
        map.put("count", Integer.valueOf(count));
        return ResultJson.ok(map);
    }

    @GetMapping({"/getTeacherWork/{teacherWorkId}"})
    public Object getTeacherWork(@PathVariable("teacherWorkId") long id) {
        TeacherWork teacherWork = this.teacherManagementService.findTeacherWorkById(id);
        return ResultJson.ok(teacherWork);
    }

    @PutMapping({"/modifyTeacherWork"})
    public Object modifyTeacherWork(@RequestBody TeacherWork teacherWork) {
        this.teacherManagementService.updateTeacherWork(teacherWork);
        return ResultJson.ok();
    }

    @PostMapping({"/addTeacherWork"})
    public Object addTeacherWork(@RequestBody TeacherWork teacherWork) {
        this.teacherManagementService.addTeacherWork(teacherWork);
        return ResultJson.ok();
    }

    @PostMapping({"/APP/uploadTeacherPhoto"})
    public Object uploadTeacherPhoto(@RequestParam("studentPhotoImage") MultipartFile file) {
        String filename = file.getOriginalFilename();
        String[] s = filename.split("_");
        String teacherId = s[0];
        Teacher teacher = this.teacherManagementService.findTeacherById(teacherId);
        if (null == teacher)
            return ResultJson.failure(ResultCode.BAD_REQUEST, ");
        try {
            byte[] bytes = file.getBytes();
            FileOutputStream fileOutputStream = FileUtils.openOutputStream(new File(this.physicalPath + this.teacherImagePath, filename));
            fileOutputStream.write(bytes);
            fileOutputStream.close();
            String imageBase64 = Base64.getEncoder().encodeToString(bytes);
            this.teacherManagementService.saveTeacherPhoto(teacher, this.teacherImagePath + "/" + filename, imageBase64);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultJson.ok();
    }
}
